package app.chatroom.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

// 自动打开浏览器
@Component
@Slf4j
@RequiredArgsConstructor
public class OpenBrowser implements CommandLineRunner {

    @Value("${server.port}")
    private int serverPort;

    @Value("${com.exe.openBrowser}")
    private boolean openBrowser = true;

    @Override
    public void run(String... args) {
        log.info("自动运行加载 网页 {}", openBrowser);
        if (openBrowser) {
            log.info("开始自动加载指定的页面");
            openBrowser();
        }
    }

    // 打开浏览器
    private void openBrowser() {
        Runtime runtime = Runtime.getRuntime();
        try {
            String os = System.getProperty("os.name").toLowerCase();
            if (os.contains("win")) {
                // Windows 系统
                runtime.exec("cmd /c start " + getLocalhostPort());
            } else if (os.contains("mac")) {
                // macOS 系统
                runtime.exec("open " + getLocalhostPort());
            } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
                // Linux/Unix 系统
                runtime.exec("xdg-open " + getLocalhostPort());
            } else {
                // 其他系统
                log.info("不支持的操作系统，无法自动打开浏览器");
            }
        } catch (Exception ex) {
            log.info("自动打开浏览器失败: {}", ex.getMessage());
        }
    }

    public String getLocalhostPort() {
        return "http://localhost:" + serverPort + "/";
    }
}

